import { _decorator, Component, EditBox, Button, Node, director } from "cc";
const { ccclass, property } = _decorator;
import { Session } from "@heroiclabs/nakama-js";
import { NakamaManager } from "./NakamaManager";
import { ToastManager } from "./ToastManager";

@ccclass("LoginManager")
export class LoginManager extends Component {
  @property(EditBox)
  usernameEditBox: EditBox = null;

  @property(EditBox)
  passwordEditBox: EditBox = null;

  @property(Button)
  loginButton: Button = null;

  private nakama = NakamaManager.getInstance();

  onLoad() {
    this.loginButton.node.on(Button.EventType.CLICK, this.onLoginClicked, this);
  }

  async onLoginClicked() {
    const email = this.usernameEditBox.string.trim();
    const password = this.passwordEditBox.string;

    if (!email || !password) {
      console.log("请输入用户名和密码");
      return;
    }
    console.log(`登录中... 用户名: ${email}, 密码: ${password}`);
    try {
      await this.nakama.loginWithEmail(email, password);
      console.log("登录成功");
      director.loadScene("lobby");
    } catch (error) {
        ToastManager.show(error.message);

        console.error("登录失败:", error);
    }
  }
}
